﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Common;
using Entities;
using System.Diagnostics;
namespace Dao
{
    /// <summary>
    /// Provides a way of query with Log from a SQL Server Database
    /// </summary>
    public class LogData
    {
        #region Vriables private
        private IList<Log> _listLog = null;
        private Log _log = null;
        #endregion

        #region Methods public
        /// <summary>
        /// Display all Log
        /// </summary>
        /// <returns>List all Logs</returns>
        public IList<Log> GetAll()
        {
            SqlConnection conn = new SqlConnection(SQLDBHelper.CONN_STRING);
            _listLog = new List<Log>();
            try
            {
                SqlDataReader reader = SQLDBHelper.ExecuteReader(conn, CommandType.StoredProcedure, "sp_Log_GetAll", null);
                while (reader.Read())
                {
                    _log = new Log();
                    if (!reader.IsDBNull(0))
                        _log.LogID = reader.GetInt32(0);
                    if (!reader.IsDBNull(1))
                        _log.LogName = reader.GetString(1);
                    if (!reader.IsDBNull(2))
                        _log.LoggedDate = reader.GetDateTime(2);
                    _listLog.Add(_log);
                }
            }
            catch (Exception ex)
            {
                ErrorManagement.TrackLog(ex.Message);
                throw ex;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            return _listLog;
        }
        /// <summary>
        /// Insert new Log
        /// </summary>
        /// <param name="log">Object of class Feedback</param>
        /// <returns>True is successful , False is unsuccessful </returns>
        public static bool Insert(string message)
        {
            SqlConnection conn = new SqlConnection(SQLDBHelper.CONN_STRING);
            int result = 0;
            try
            {
                SqlParameter[] parms = new SqlParameter[] {
                     new SqlParameter("@message", SqlDbType.NText),
                     new SqlParameter("@dateTime", SqlDbType.DateTime)
                };
                Log log = new Log(message, DateTime.Now);
                parms[0].Value = log.LogName;
                parms[1].Value = log.LoggedDate;

                result = SQLDBHelper.ExecuteNonQuery(conn, CommandType.Text, "Insert into Log values(@message,@dateTime)", parms);

            }
            catch (Exception ex)
            {
                //Then finish Project will return value null;
                throw ex;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            return result > 0 ? true : false;
        }
        public bool Update(Log log)
        {
            SqlConnection conn = new SqlConnection(SQLDBHelper.CONN_STRING);
            int result = 0;
            try
            {
                SqlParameter[] parms = new SqlParameter[]{
                    new SqlParameter("@LogID", SqlDbType.Int, 2),
                    new SqlParameter("@LogName", SqlDbType.NVarChar, 200)
            };
                parms[0].Value = log.LogID;
                parms[1].Value = log.LogName;

                result = SQLDBHelper.ExecuteNonQuery(conn, CommandType.Text, "update Log set LogName = @LogName where LogID = @LogID", parms);
            }
            catch (Exception ex)
            {
                ErrorManagement.TrackLog(ex.Message);
                throw ex;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            return result > 0 ? true : false;
        }
        public IList<Log> SortByColumn(string nameColumn)
        {
            SqlConnection conn = new SqlConnection(SQLDBHelper.CONN_STRING);
            try
            {
                SqlDataReader reader = SQLDBHelper.ExecuteReader(conn, CommandType.Text, "select  * from Log order by " + nameColumn + " asc", null);
                _listLog = new List<Log>();
                while (reader.Read())
                {
                    _log = new Log();
                    if (!reader.IsDBNull(0))
                        _log.LogID = reader.GetInt32(0);
                    if (!reader.IsDBNull(1))
                        _log.LogName = reader.GetString(1);
                    if (!reader.IsDBNull(2))
                        _log.LoggedDate = reader.GetDateTime(2);
                    _listLog.Add(_log);
                }
            }
            catch (Exception ex)
            {
                ErrorManagement.TrackLog(ex.Message);
                throw ex;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            return _listLog;
        }
        public IList<Log> SearchByTitle(string tilte)
        {
            SqlConnection conn = new SqlConnection(SQLDBHelper.CONN_STRING);
            try
            {
                SqlParameter[] parm = new SqlParameter[] { new SqlParameter("@LogName", SqlDbType.NVarChar, 150) };
                parm[0].Value = tilte;
                SqlDataReader reader = SQLDBHelper.ExecuteReader(conn, CommandType.Text, "select * from Log where LogName like '%' +@LogName+ '%'", parm);
                _listLog = new List<Log>();
                while (reader.Read())
                {
                    _log = new Log();
                    if (!reader.IsDBNull(0))
                        _log.LogID = reader.GetInt32(0);
                    if (!reader.IsDBNull(1))
                        _log.LogName = reader.GetString(1);
                    if (!reader.IsDBNull(2))
                        _log.LoggedDate = reader.GetDateTime(2);
                    _listLog.Add(_log);

                }
            }
            catch (Exception ex)
            {
                ErrorManagement.TrackLog(ex.Message);
                throw ex;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            return _listLog;
        }
        /// <summary>
        /// Delete a log
        /// </summary>
        /// <param name="logID">ID of Log want to delete</param>
        /// <returns>True is successful , False is unsuccessful </returns>
        public bool DeleteByID(int logID)
        {
            SqlConnection conn = new SqlConnection(SQLDBHelper.CONN_STRING);
            int result = 0;
            try
            {
                SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@LogID", SqlDbType.Int, 2) };
                parms[0].Value = logID;
                result = SQLDBHelper.ExecuteNonQuery(conn, CommandType.Text, "delete from Log where LogID = @LogID", parms);
            }
            catch (Exception ex)
            {
                ErrorManagement.TrackLog(ex.Message);
                throw ex;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            return result > 0 ? true : false;
        }
        #endregion
    }
    public class ErrorManagement
    {
        public static void TrackLog(string errorMessage)
        {
            StackTrace _st = new StackTrace(true);
            string _stackIndent = "";
            string message = string.Empty;
            for (int i = 1; i < _st.FrameCount; i++)
            {
                StackFrame _sf = _st.GetFrame(i);
                string a = string.Format(_stackIndent + " Method: {0}",
                     _sf.GetMethod());
                string a1 = string.Format(_stackIndent + " File: {0}",
                     _sf.GetFileName());
                string a2 = string.Format(_stackIndent + " Line Number: {0}",
                     _sf.GetFileLineNumber());
                string a3 = string.Format(_stackIndent + " Desciption error: {0}",
                  errorMessage);
                string a4 = string.Format(_stackIndent + " Date time: {0}",
                 DateTime.Now);
                _stackIndent += "  ";

            }
            LogData.Insert(message);
        }
    }
}
